<?php

namespace App\Notifications;


use App\Channels\SmsChannel;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Log;
use App\Admin\Repositories\ProjectAgreement;
use App\Models\AdminUser;
use App\Models\Project;
use App\Services\SmsService;

class AuditNotify extends Notification implements ShouldQueue
{
    use Queueable;

    // 审批完以后的协议
    protected $agreementModel;

    // 审批log
    protected $auditLog = [];

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct($model = null)
    {
        $this->agreementModel = $model;

        if ($this->agreementModel->audit_log) {
            $this->auditLog = json_decode($this->agreementModel->audit_log, true);
        }
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param mixed $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        // return ['mail', SmsChannel::class];
        // return ['mail', 'Sms'];
        return [SmsChannel::class];
    }


    /**
     * Get the mail representation of the notification.
     *
     * @param mixed $notifiable
     * @return MailMessage
     */
    public function toMail($notifiable)
    {
        Log::info('------ 发送邮件 ------' . json_encode($notifiable));
        if (!$notifiable->email) {
            Log::error('未找到当前用户的邮件地址! userinfo: ' . json_encode($notifiable));
            return false;
        }
        return (new MailMessage)
            ->subject('审核通知')
            ->greeting('Hello')
            ->from('yang.zhang@innovindex.com')
            ->line('关于妥付协议审核通知')
            ->action('点击查看', url('/'))
            ->line('Thank you for using our application!');
    }

    /**
     * Get the array representation of the notification.
     *
     * @param mixed $notifiable
     * @return array
     */
    public function toSms($notifiable)
    {
        Log::info('------ 发送短信 ------' . json_encode($notifiable));
        // 加载语言包
        $path = rtrim(app()->langPath(), '/') . '/' . App::getLocale() . '/' . 'agreement-manage.php';
        $lang = include $path;

        $flowMap = ProjectAgreement::getFlowMap();
        $lastLog = end($this->auditLog);
        Log::info('====== 协议数据 ======' . $this->agreementModel);
        Log::info('====== 审核记录： ======' . $this->agreementModel->audit_log);
        if (empty($lastLog)) {
            return '';
        }
        // $column = $lang['fields'][$flowMap[$lastLog['audit_global_status']]];
        $auditStatusMap = ProjectAgreement::getAuditStatus($flowMap[$lastLog['audit_global_status']]);
        // 查询项目名
        $projectName = Project::find($this->agreementModel->project_id)->project_name ?? '项目名称';
        // 拼接项目名
        // $msg = $column . ': ' . $auditStatusMap[$lastLog['audit_status']];
        $auditStatus = $auditStatusMap[$lastLog['audit_status']];
        if ($lastLog['audit_status'] <> 1 && $lastLog['audit_remark']) {
            // $msg .= ", " . $lang['fields'][$lastLog['audit_remark']] . ": " . $lastLog['audit_remark'];
            $remark = $lastLog['audit_remark'];
        }

        $notice = [];
        // todo 判断状态发送审核成功、或者审核失败的短信。
        if ($lastLog['audit_status'] == 1) {
            // 成功
            $template = 'AUDIT_SUCCESS';
            $notice = [000000];
        } elseif ($lastLog['audit_status'] == -1) {
            $template = 'AUDIT_FAIL';
            $notice = ['《' . $projectName . '》' . ' - ' . '专家：' . $notifiable->realname, $auditStatus, $remark];
        }

        Log::info(' ====== notice ====== ' . json_encode($notice));
        // 查找对应代理人手机号，给代理人发送短信通知
        $agent = AdminUser::where('id', $notifiable->agent)->first();
        if (!empty($agent)) {
            $phone = $agent['phone'];

            SmsService::sendCode($phone, $notice, $template);
            Log::info('Send  AuditNotify ' . $phone . json_encode($notice));
        } else {
            return '';
        }
    }
}
